<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <template #header>
        <el-button type="primary" icon="ele-Plus" @click="TMAdd">添加</el-button>
      </template>
      <!-- card body -->
      <el-table :data="tabelData" border stripe>
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column label="品牌名称" prop="tmName" />
        <el-table-column label="品牌logo" prop="logoUrl">
          <!-- 表格作用域插槽的作用域数据row代表当前行完整数据 $index代表当前数据的下标 -->
          <template v-slot="{ row }">
            <el-image style="height: 100px" :src="row.logoUrl" fit="fill" :lazy="true"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="warning" size="small" icon="ele-Edit" @click="TMUpdate(row)">修改</el-button>
            <el-popconfirm title="是否确认删除" @confirm="confirmDelete(row.id)">
              <template #reference>
                <el-button type="danger" size="small" icon="ele-Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-model:page-size="pageSize" :page-count="pageCount" :pager-count="5" :page-sizes="[3, 5, 7, 9]"
        :total="totals" v-model:current-page="currentPage" layout="total, prev, pager, next, sizes" />
    </el-card>

    <!-- 添加和修改的弹窗 -->
    <el-dialog v-model="dialogVisible" :title="TMDate.id ? '修改品牌' : '添加品牌'">
      <el-form label-width="120px" :rules="rules" :model="TMDate" ref="formEle">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="TMDate.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload class="avatar-uploader" action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="TMDate.logoUrl" :src="TMDate.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <ele-Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false;">取消</el-button>
          <el-button type="primary" @click="TMAddOrUpdate"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "Trademark",
});
</script>
  
<script setup lang="ts">
import { ref, onMounted, watch, reactive } from "vue";
import type { FormInstance, FormRules, UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
import { type tmLlistType, type tmItemType, reqUpdateTM, reqAddTM, reqDelTM } from "@/api/trademark"
import useTMListStore from "@/stores/trademark"
const TMStore = useTMListStore()
const tabelData = ref<tmLlistType>([])
// 每页条数
const pageSize = ref(3)

// 总页数
const pageCount = ref(100)

// 当前页
const currentPage = ref(1)

// 总页数
const totals = ref(1)

const TMList = async () => {
  try {
    await TMStore.getTM(currentPage.value, pageSize.value)
    tabelData.value = TMStore.TMList
    pageCount.value = TMStore.page
    totals.value = TMStore.total
  } catch (e) {
    return Promise.reject(e)
  }
}

onMounted(() => {
  TMList()
}),

  watch([pageSize, currentPage], () => {
    TMList()
  })

//定义一个新增或者修改的品牌数据
const TMDate = ref<tmItemType>({
  tmName: "",
  logoUrl: "",
});


//弹窗控制显示隐藏的数据定义
const dialogVisible = ref(false);

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response
) => {
  TMDate.value.logoUrl = response.data;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

const formEle = ref<FormInstance>()
// 点击按钮添加的函数
const TMAdd = () => {
  // 清空表单校验提示
  formEle.value?.clearValidate()
  TMDate.value = {
    tmName: "",
    logoUrl: "",
  };
  dialogVisible.value = true;
}
// 点击按钮修改的函数
const TMUpdate = (row: tmItemType) => {
  formEle.value?.clearValidate()
  TMDate.value = { ...row }
  dialogVisible.value = true;
}

// 添加 or 修改的函数
const TMAddOrUpdate = async () => {
  // 整体校验
  try {
    const re = await formEle.value?.validate()
    if (!re) {
      return
    }
  } catch (e) {
    return
  }
  try {
    if (TMDate.value.id) {
      await reqUpdateTM(TMDate.value)
      ElMessage.success("更新成功")
    } else {
      await reqAddTM(TMDate.value)
      ElMessage.success("添加成功")
    }
  } catch (e: any) {
    ElMessage.error(e.message)
  }
  //关闭弹窗
  dialogVisible.value = false;
  // 重新获取数据
  TMList();
}

// 删除某个
const confirmDelete = async (id: number) => {
  try {
    // 请求删除
    await reqDelTM(id)
    // 重新渲染
    TMList()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

// 表单校验
const rules = reactive<FormRules>({
  tmName: [{ required: true, message: "品牌名称不能为空", trigger: "blur" }],
  logoUrl: [{ required: true, message: "品牌的logo不能为空", trigger: "blur" }],
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>